<template>
	<view class="wrap">
		<view class="tab_box flex_sa">
			<view class="tab_item flex_c" :class="{active:tabCurrent==index}" v-for="(item,index) in tabList"
				:key="index" @click="changeTab(index)">
				{{item.name}}
			</view>
		</view>
		<view class="time_box" v-if="tabCurrent==3">
			<uni-datetime-picker v-model="range" type="daterange" @change="changeHandler">
				{{range.join('/')}} <text class="iconfont icon-xiangxia"></text>
			</uni-datetime-picker>

		</view>
		<view class="table_box">
			<uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="90" align="center">
						<view class="table_th">
							商品名称
						</view>
					</uni-th>
					<uni-th width="44" align="center">
						<view class="table_th">
							克重
						</view>

					</uni-th>
					<uni-th width="60" align="center">
						<view class="table_th">
							工费/克
						</view>
					</uni-th>
					<uni-th width="60" align="center">
						<view class="table_th">
							附加/件
						</view>
					</uni-th>
					<uni-th width="44" align="center">
						<view class="table_th">
							数量
						</view>
					</uni-th>
					<uni-th width="60" align="center">
						<view class="table_th">
							总金额
						</view>
					</uni-th>
				</uni-tr>

				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td align="center" width="90">
						<view class="table_td line1 title_box">{{ item.product_name }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td">{{ item.weight }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td">{{ item.labor_costs }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td">{{ item.attach_labor_costs }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td">{{ item.sum }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td">{{ item.total_price }}</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<view class="loading_box" v-if="tableData.length > 0">
			<text class="loading iconfont icon-jiazai" :hidden="loading == false"></text>
		</view>
		<view class="footer">
			<view class="top_box flex_sb">
				<view class="left_box">
					共：{{infoData.count}}单，总计：<text>¥{{infoData.total_total_price}}</text>
				</view>

				<view class="btn_box flex_s">
					<view class="btn_item" :class="{'gray_btn':keyLock}" @click="outputHandler">
						导出
					</view>
					<view class="btn_item" @click="$util.JumpPath('/pages/new_page/statementAccount/myDownload')">
						下载
					</view>

				</view>
			</view>
			<view class="btm_box flex_sa">
				<view class="item_box">
					<view class="text1">
						克重
					</view>
					<view class="text2">
						{{infoData.total_weight}}克
					</view>
				</view>
				<view class="item_box">
					<view class="text1">
						工费
					</view>
					<view class="text2">
						{{infoData.total_labor_costs}}
					</view>
				</view>
				<view class="item_box">
					<view class="text1">
						附加工费
					</view>
					<view class="text2">
						{{infoData.total_attach_labor_costs}}
					</view>
				</view>
				<view class="item_box">
					<view class="text1">
						数量
					</view>
					<view class="text2">
						{{infoData.total_sum}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		statement_list,
		statement_export
	} from "@/api/new_api.js"
	export default {
		data() {
			return {
				tabCurrent: 0,
				tabList: [{
					name: '今天',
					id: 'today'
				}, {
					name: '本周',
					id: 'nowweek'
				}, {
					name: '本月',
					id: 'nowmonth'
				}, {
					name: '自定义',
					id: 1
				}],
				tableData: [],
				range: [],
				infoData: {},
				page: 1,
				limit: 10,
				loadend: false, //是否加载完毕
				loading: false, //是否加载中
				outputUrl: '',
				keyLock: false,
				schedule: 0, //下载进度1-100%
				filePath: ''

			}
		},
		onReachBottom() {
			if (this.loadend) return;
			if (this.loading) return;
			this.page++;
			this.initData()
		},
		onLoad() {
			console.log(wx.env.USER_DATA_PATH, "路径");
			this.range = this.getCurrentDateRange()
			this.initData()
		},
		methods: {
			// 获取当前时间，文件命名
			generateTimestampFileName() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}${month}${day}${hours}${minutes}${seconds}`;
			},
			actionSheetTap() {
				const that = this
				// wx.shareFileMessage({
				// 	filePath: that.filePath,
				// 	fileType: `xls`,
				// 	success(data) {
				// 		console.log('转发成功！！！', data)
				// 	},
				// 	fileName:that.filePath,
				// 	fail: console.error,
				// })
				// return
				uni.showActionSheet({
					itemList: ['分享到好友', '添加到收藏'],
					success: e => {
						if (e.tapIndex == 0) {
							uni.shareFileMessage({
								filePath: that.filePath,
								fileName: `${that.generateTimestampFileName()}.xlsx`,
								success(res) {
									console.log(res, "分下成功")
								},
								fail: console.error
							})
						} else {
							uni.addFileToFavorites({
								filePath: that.filePath,
								fileName: `${that.generateTimestampFileName()}.xlsx`,
								success(res) {
									console.log(res, "收藏成功")
								},
								fail: console.error
							})
						}
					}
				});

			},
			async downloadHandler() {
				let that = this
				if (!this.outputUrl) {
					await this.statement_export()
				}
				const downloadTask = uni.downloadFile({
					url: 'https://ybl.jinxiaodu.com/phpExcel/202507/24/420250724165223.xlsx',
					filePath: `${wx.env.USER_DATA_PATH}/${that.generateTimestampFileName()}.xlsx`,
					success: res => {
						if (res.statusCode === 200) {
							that.filePath = res.filePath
							// this.isShowProgress = false;
							console.log('下载成功', res.filePath);
						}
						that.actionSheetTap()
						// uni.saveFile({
						// 	tempFilePath: that.filePath,
						// 	success: function(red) {
						// 		that.isShowProgress = false;
						// 		uni.showModal({
						// 			title: '提示',
						// 			content: '文件已保存：' + red.savedFilePath,
						// 			cancelText: '我知道了',
						// 			confirmText: '打开文件',
						// 			success: function(res) {
						// 				if (res.confirm) {
						// 					uni.openDocument({
						// 						filePath: red
						// 							.savedFilePath,
						// 						showMenu: true,
						// 						success: (sus) => {
						// 							console.log(
						// 								'成功打开');
						// 						}
						// 					})
						// 				}
						// 			}
						// 		});
						// 	}
						// });
					}
				})

				downloadTask.onProgressUpdate((res) => {
					if (res.progress > 0) {
						this.isShowProgress = true;
					}
					this.progress = res.progress;
					console.log('下载进度：' + res.progress);
					console.log('已下载长度：' + res.totalBytesWritten);
					console.log('文件总长度：' + res.totalBytesExpectedToWrite);
				})
			},
			// 预览图片和文件成功
			async previewFile() {
				// 流程步骤: 利用下载文件功能 先生成临时文件 - 调用api打开临时文件里面的内容,从而生成预览的效果,但是这个未能真实的下载到本地
				// 1.pdfUrl  可以直接在浏览器打开  2.一定要在小程序后台配置该pdf的域名 让其可以下载
				// uni.showLoading({
				// 	title: '正在打开...'+ this.schedule+'%'
				// });
				let that = this
				this.schedule = 0; //载入进度为0
				if (!this.outputUrl) {

					await this.statement_export()
				}
				const downloadTask = uni.downloadFile({
					url: 'https://ybl.jinxiaodu.com/phpExcel/202507/24/420250724165223.xlsx', // 图片或者文件地址
					filePath: `${wx.env.USER_DATA_PATH}/${that.generateTimestampFileName()}.xlsx`,
					success: function(res) {
						console.log('下载的res', res);
						var filePath = res.filePath; // 临时文件存储路径
						//  文件打开文件预览
						uni.openDocument({
							filePath: encodeURI(filePath),
							showMenu: true,
							// fileType: 'pdf',
							success: function(res) {
								uni.hideLoading();
							},
							fail: function(err) {
								uni.hideLoading();
								uni.showToast({
									title: '打开失败',
									duration: 1500,
									icon: 'none'
								});
								console.log('打开失败');
							}
						});
					},
					fail: function(err) {
						console.log('下载失败原因', err);
						uni.hideLoading();
						uni.showModal({
							title: '您需要授权相册权限',
							success(res) {
								if (res.confirm) {
									uni.openSetting({
										success(res) {},
										fail(res) {
											console.log(res);
										}
									});
								}
							}
						});
					}
				});
				downloadTask.onProgressUpdate(res => {
					console.log('下载进度' + res.progress);
					this.schedule = res.progress
					// console.log('已经下载的数据长度' + res.totalBytesWritten);
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
				});
				// console.log(item, this.$url(item.template), '加载的当前文件');
				// this.$apiGet(`/api/file/download/${item.template}`).then(res => {
				// 	console.log(res, '下载的文件');
				// });
			},
			clearData() {
				this.page = 1
				this.loading = false
				this.loadend = false
				this.tableData = []
				this.outputUrl = ""
			},
			initData() {

				this.statement_list()

			},
			statement_list() {

				this.loading = true;
				const parmas = {
					page: this.page,
					limit: this.limit,
					day_type: this.tabList[this.tabCurrent].id,
					search_time_str: this.range[0],
					search_time_end: this.range[1]
				}
				statement_list(parmas).then((res) => {
					// let list = []
					// for (var index = 0; index < 50; index++) {
					// 	list.push(...res.data.list)

					// }
					let list = res.data.list || []
					this.loadend = list.length < this.limit
					this.tableData = this.tableData.concat(list)
					this.infoData = res.data
					this.loading = false;


				}).catch(err => {
					this.loading = false;
				});
			},
			outputHandler() {
				if (this.infoData.count == 0) return this.$util.Tips({
					title: '暂无数据'
				})
				if (this.keyLock) return
				uni.showLoading({
					title: "导出中...",
				})
				this.keyLock = true
				this.statement_export()
			},
			statement_export() {
				let that = this
				const parmas = {
					page: this.page,
					limit: this.limit,
					day_type: this.tabList[this.tabCurrent].id,
					search_time_str: this.range[0],
					search_time_end: this.range[1]
				}
				statement_export(parmas).then((res) => {
					this.keyLock = false
					// const data = res.data
					this.$util.Tips({
						title: res.msg
					})
					// this.outputUrl = data.url
					// if (!this.outputUrl) return this.$util.Tips({
					// 	title: '导出链接为空'
					// })
					// uni.setClipboardData({
					// 	data: this.outputUrl,
					// 	success: () => {
					// 		that.$util.Tips({
					// 			title: '链接已复制,请在浏览器中打开',
					// 			endtime: 2000
					// 		})
					// 	}
					// })
				}).catch(() => {
					this.keyLock = false
				})
			},
			getCurrentDateRange() {
				const today = new Date();

				// 获取年、月、日
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(today.getDate()).padStart(2, '0');

				// 当前日期字符串
				const currentDate = `${year}-${month}-${day}`;

				return [currentDate, currentDate];
			},
			changeTab(e) {
				if (this.tabCurrent == e) return
				this.tabCurrent = e
				this.clearData()
				this.initData()
			},

			changeHandler(e) {
				this.clearData()
				this.initData()
				console.log('changeHandler事件:', e);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.loading_box {
		text-align: center;
	}

	::v-deep .uni-table {

		// 改表头字体样式

		.uni-table-th {
			border-right: none;
			background: #F4F5F6;
			font-size: 24rpx;
			font-weight: normal;
			color: #9E9E9E;
		}
	}
	.title_box{
		width: 180rpx;
	}
	.table_td {
		// white-space: nowrap;
		font-size: 26rpx;
		color: #363636;
	}

	.wrap {
		padding-bottom: 400rpx;

		.footer {
			background: #fff;
			width: 100%;
			position: fixed;
			left: 0;
			bottom: 0;
			padding-bottom: 50rpx;
			border: 1rpx solid #E5E5E5;

			.top_box {
				padding: 25rpx 30rpx;
				border-bottom: 2rpx solid #F4F5F6;

				.left_box {
					font-size: 26rpx;
					color: #737272;

					text {
						color: #D43030;
					}
				}

				.btn_box {

					.btn_item {
						padding: 15rpx 30rpx;
						color: #fff;
						font-size: 30rpx;
						background: #43CF7C;
						border-radius: 11rpx;
						margin-left: 10rpx;
					}
				}

				.gray_btn {
					background: #ccc;
				}

			}

			.btm_box {
				padding: 20rpx 0;

				.item_box {
					position: relative;
					text-align: center;
					flex: 1;

					&:not(:first-child)::before {
						position: absolute;
						left: 0;
						top: 50%;
						transform: translateY(-50%);
						content: "";
						width: 1rpx;
						height: 80rpx;
						background: #E5E5E5;
					}

					.text1 {
						color: #737272;
						margin-bottom: 5rpx;
					}

					.text2 {
						color: #424040;
					}
				}
			}
		}

		.time_box {
			font-size: 30rpx;
			color: #000;
			margin: 30rpx 0;
			padding-left: 30rpx;

			.iconfont {
				margin-left: 10rpx;
				font-size: 26rpx;
				font-weight: bold;
			}
		}

		.tab_box {
			position: sticky;
			top: 0;
			z-index: 10;
			width: 100%;
			height: 76rpx;
			// padding: 0 150rpx;
			background: #FFF;

			.tab_item {
				font-size: 34rpx;
				height: 100%;
				color: #383838;
				border-bottom: 6rpx solid transparent;

			}

			.active {
				color: #643400;
				border-bottom: 6rpx solid #643400;
			}

		}

		.table_box {
			width: 100%;
		}
	}

	.content_box {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		border-radius: 20rpx;
		color: #000;
		background: #fff;
		font-size: 40rpx;
		padding: 20rpx 30rpx;
		text-align: center;
	}
</style>